/**
 * 
 */
package org.vsg.stock.dzh;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.vsg.common.configration.PropertiesSupport;
import org.vsg.stock.basic.persistence.StockInfoDao;

/**
 * @author vison
 *
 */
public class GenerateAllDailyLine {

	private final static Logger logger = LoggerFactory.getLogger(GenerateDailyLine.class);	

	
	private File dzh2Txt;

	private String encoding;
	
	
	public void exec(ApplicationContext appContext) throws Exception {

		PropertiesSupport proSupport = (PropertiesSupport)appContext.getBean("propertyConfigurer");
		
		String propDailyLine = proSupport.getProperties().getProperty("stock.dailyline.dir");
		if (propDailyLine == null) {
			//logger.warn("Property 'stock.dailyline.dirk' is not defined! ");
			throw new Exception("Property 'stock.dailyline.dir' is not defined!");
		}
		File dailLineDir = new File(propDailyLine);

		String dzh2txtStr = proSupport.getProperties().getProperty("dzh2txt");
		if (dzh2txtStr == null) {
			//logger.warn("Property 'stock.dailyline.dirk' is not defined! ");
			throw new Exception("Property 'dzh2txt' is not defined!");
		}
		dzh2Txt = new File(dzh2txtStr);
		
		encoding = proSupport.getProperties().getProperty("file.encoding");

		File dailyFilePath = new File(dailLineDir , "all-stocks.txt");		

		StockInfoDao stockInfoDao = (StockInfoDao)appContext.getBean("stockInfoDao");			
		// --- reade the content ---
		List<String> allStkCodes = stockInfoDao.findAllCode();

		List<String> lines = null;
		
		String lineEnding = "\n";

		OutputStream os = null;
		try {
			os = new BufferedOutputStream( new FileOutputStream( dailyFilePath) );
			
			String stkCode = null;
			
			List<String> newLines = null;
			for (Iterator<String> allStockCodesIter = allStkCodes.iterator() ; allStockCodesIter.hasNext();) {
				stkCode = allStockCodesIter.next();
				
				newLines = new LinkedList<String>();
				
				lines = hqExecCommand(stkCode);
				Collections.reverse( lines );				
				for (int i = 0 ; i < lines.size() ; i++) {
					String line = lines.get(i);
					line = DataConverter.convert(lines, i, line);
					newLines.add( line );
				}
				lines.clear();
				lines = null;
				
				IOUtils.writeLines(newLines, lineEnding , os);		
				
				logger.debug( "gen stock daily \""+stkCode+"\" , ok! " );

			}
	
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		
		} finally {
			
			if (os != null) {
				
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}			
		
	}

	private List<String> hqExecCommand(String stockCode) {
		
		Runtime runtime = Runtime.getRuntime();
		
		StringBuffer cmd = new StringBuffer( dzh2Txt.getAbsolutePath() );
		cmd.append(" ");
		cmd.append("getdata ").append("hqfq ");
		cmd.append(stockCode);

		List<String> list = new ArrayList();
		InputStream is = null;
		try {
			Process proc = runtime.exec(cmd.toString());
			
			is = proc.getInputStream();
			// using buffer inputstream 
			InputStreamReader reader = new InputStreamReader(is, encoding);
			BufferedReader breader = new BufferedReader(reader);
			String line =breader.readLine();
			 while (line != null) {
			  	// --- parse object---
			    list.add(line);
			    line = breader.readLine();
			  }
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					is = null;
				}
			}
		}
	        
	     return list;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		ClassLoader clsLoader = GenerateDailyLine.class.getClassLoader();
		// --- run the main page ---
		// build the read the path , dzh's home path
		String[] configContextFiles = {
				"classpath:/spring/configurationContext.xml",
				"classpath*:/spring/applicationContext.xml",
				"classpath*:/spring/dataAccessContext.xml"
		};
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext(configContextFiles,true);
		
	
		GenerateAllDailyLine mainProg = new GenerateAllDailyLine();
		
		try {
			mainProg.exec(ctx);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		logger.info("program run ... Ok!");
	}

}
